package com.ruoyi.salesman.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.recycle.domain.SalesmanManagement;
import com.ruoyi.recycle.dto.LoginDTO;
import com.ruoyi.recycle.exception.BusinessException;
import com.ruoyi.recycle.properties.Wxproperties;
import com.ruoyi.recycle.service.ISalesmanManagementService;
import com.ruoyi.recycle.vo.LoginVO;
import com.ruoyi.salesman.service.LoginService;
import com.ruoyi.system.api.RemoteLoginService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.form.LoginBody;
import com.ruoyi.system.api.model.LoginUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private Wxproperties wxproperties;
    @Resource
    private ISalesmanManagementService salesmanManagementService;
    @Resource
    private RemoteLoginService remoteLoginService;
    @Resource
    private RemoteUserService userService;

    @Override
    public String wechatAuth(String code, String encryptedData, String iv) {
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid="
                + wxproperties.getSalesmanAppId() + "&secret="
                + wxproperties.getSalesmanAppSecretKey() + "&js_code="
                + code
                + "&grant_type=authorization_code");
        final JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("openid");
    }

    @Override
    @SneakyThrows
    public LoginVO login(LoginDTO loginDTO) {
        final SalesmanManagement account = salesmanManagementService.getOne(Wrappers.lambdaQuery(new SalesmanManagement())
                .eq(SalesmanManagement::getSalesmanNumber, loginDTO.getUsername()));
        if (Objects.isNull(account)) {
            throw new Exception("找不到该账号");
        }
        if (StrUtil.isEmpty(account.getOpenid())) {
            throw new BusinessException(StrUtil.format("无法获取用户openId,请先进行微信授权,以获取用户微信信息"));
        }
        if (StrUtil.isNotEmpty(loginDTO.getOpenId())) {
            account.setOpenid(loginDTO.getOpenId());
            salesmanManagementService.updateById(account);
        }
        final R<?> login = remoteLoginService.login(new LoginBody()
                .setUsername(loginDTO.getUsername())
                .setPassword(loginDTO.getPassword()));
        final Map<String, Object> data = (Map<String, Object>) login.getData();
        final R<LoginUser> userInfo = userService.getUserInfo(loginDTO.getUsername(), SecurityConstants.INNER);
        return new LoginVO().setSalesmanManagement(account)
                .setUserInfo((userInfo.getData()))
                .setToken(data.get("access_token"))
                .setExpireTime(data.get("expires_in"));
    }

    @Override
    public R logout(HttpServletRequest request) {
        try {
            return remoteLoginService.logout(request);
        } catch (Exception e) {
            log.error("业务员用户登出操作产生错误,原因:{}", e.getMessage());
            return R.fail();
        }
    }
}
